/**
 *
 */
package jMiiEditor.gui.miifilechooser;

import jMiiEditor.mii.Mii;
import jMiiEditor.mii.checker.MiiCheckerFileObject;
import jMiiEditor.mii.checker.impl.MiiCheckerFileObjectVFSImpl;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import net.sf.vfsjfilechooser.utils.VFSUtils;
import org.apache.commons.vfs.FileContent;
import org.apache.commons.vfs.FileObject;

/**
 * @author CC
 *
 */
public class MiiFileObjectVFSImpl implements MiiFileObject
{
    private FileObject aFileObject;

    /**
     * @param aFileObject
     *
     */
    public MiiFileObjectVFSImpl( FileObject aFileObject )
    {
        this.aFileObject = aFileObject;
    }

    @Override
    public String getDisplayPath()
    {
        return VFSUtils.getFriendlyName(aFileObject.toString());
    }

    @Override
    public String getName()
    {
        return aFileObject.getName().toString();
    }

    @Override
    public boolean exists()
    {
        try {
            if( this.aFileObject.isWriteable() ) {
//                AbstractFileObject abstractFileObject = FileObjectUtils.getAbstractFileObject( aFileObject );
//                InputStream is = abstractFileObject.getInputStream();
                FileContent aFileContent = aFileObject.getContent();
                InputStream is           = aFileContent.getInputStream();

                if( is != null ) {
                    is.close();
                    return true;
                }
            }
            return false;
        }
        catch( IOException e ) {
            return false;
        }
    }

    @Override
    public Mii loadMii() throws IOException
    {
        FileContent aFileContent = aFileObject.getContent();
        InputStream is           = aFileContent.getInputStream();
        Mii         newMii       = new Mii( is );
        
        is.close();
        
        return newMii;
    }

    @Override
    public void saveMii(Mii mii) throws IOException
    {
        FileContent  aFileContent = aFileObject.getContent();
        OutputStream os           = aFileContent.getOutputStream();
        
        mii.save( os );
        os.close();
    }

    @Override
    public MiiCheckerFileObject getMiiCheckerFileObject()
    {
        return new MiiCheckerFileObjectVFSImpl(aFileObject);
    }
    
    @Override
    public MiiFileObject getMiiFileObject(
            MiiCheckerFileObject aMiiCheckerFileObject 
            )
    {
        FileObject f = FileObject.class.cast( 
                aMiiCheckerFileObject.getInternalObject()
                );
        
        return new MiiFileObjectVFSImpl( f );
    }

}
